//
//  AddNewAddressViewController.m
//  customer
//
//  Created by Holothurian on 2018/11/3.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "AddNewAddressViewController.h"
#import "DecorateAppointMultiTableViewCell.h"

static NSString *InputTextIDentifier = @"InputTextIDentifier";
static NSString *PositionSelectIDentifier = @"PositionSelectIDentifier";
@interface AddNewAddressViewController ()<UITableViewDelegate,UITableViewDataSource,DecorateTapSelectTableCellDelegate>

@property (nonatomic,strong)NSMutableArray *keyArray;

@property (nonatomic,strong)NSMutableArray *valueArray;

@property (nonatomic,strong)NSMutableArray *placeArray;

@property (nonatomic,strong)DecorateLocationModel *locationModel;

@end

@implementation AddNewAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"添加地址";
    [self crateView];
}

- (void)crateView{
    self.tableView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, F_DEVICE_W, F_DEVICE_H - NAVIGATION_BAR_HEIGHT - bottomPadding(0));
    self.tableView.bounces = NO;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[DecorateAppointInputTextTableCell class] forCellReuseIdentifier:InputTextIDentifier];
    [self.tableView registerClass:[DecorateAppointPositionSelectTableCell class] forCellReuseIdentifier:PositionSelectIDentifier];
    
    [self.keyArray addObjectsFromArray:@[@"报修人",@"联系电话",@"报修地址",@"详细地址"]];
    [self.placeArray addObjectsFromArray:@[@"请输入姓名",@"请输入手机号码",@"点击选择地址",@"街道名称门牌号"]];
    self.locationModel = [[DecorateLocationModel alloc]init];
    if (self.isEdit) {
        self.locationModel.province = self.addressModel.address_province;
        self.locationModel.city = self.addressModel.address_city;
        self.locationModel.country = self.addressModel.address_country;
        self.locationModel.detail = self.addressModel.address_detailed;
        self.locationModel.number = self.addressModel.address_road;
        self.locationModel.citycode = self.addressModel.address_zip_code;
        self.locationModel.longitude = [NSString stringWithFormat:@"%@",self.addressModel.address_longitude];
        self.locationModel.latitude = [NSString stringWithFormat:@"%@",self.addressModel.address_latitude];
        [self.valueArray addObjectsFromArray:@[
                                               self.addressModel.address_name,
                                               self.addressModel.address_mobile,
                                               [NSString stringWithFormat:@"%@%@%@",self.addressModel.address_province,self.addressModel.address_city,self.addressModel.address_country],
                                               [NSString stringWithFormat:@"%@%@",self.addressModel.address_detailed,self.addressModel.address_road]]];
    }else{
        [self.valueArray addObjectsFromArray:@[@"",@"",@"",@""]];
    }    
}

- (void)addNewAddress{
    if (k_Is_Empty(self.valueArray[0])) {
        [self showErrorTipWithTitle:@"请输入姓名"];
        return;
    }
    if (k_Is_Empty(self.valueArray[1])) {
        [self showErrorTipWithTitle:@"请输入手机号码"];
        return;
    }
    if (k_Is_Empty(self.valueArray[2])) {
        [self showErrorTipWithTitle:@"点击选择地址"];
        return;
    }
    if (k_Is_Empty(self.valueArray[3])) {
        [self showErrorTipWithTitle:@"街道名称门牌号"];
        return;
    }
    AutoWeakSelf
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:K_UserDefault_Read(CustomerUserID)?:@"" forKey:@"member_id"];
    [dict setObject:K_UserDefault_Read(CustomerUserToken)?:@"" forKey:@"member_token"];
    [dict setObject:self.valueArray[0] forKey:@"address_name"];
    [dict setObject:self.valueArray[1] forKey:@"address_mobile"];
    [dict setObject:self.locationModel.province forKey:@"address_province"];
    [dict setObject:self.locationModel.city forKey:@"address_city"];
    [dict setObject:self.locationModel.country forKey:@"address_country"];
    [dict setObject:self.valueArray[3]?:@"" forKey:@"address_detailed"];
    [dict setObject:self.locationModel.number?:@"" forKey:@"address_road"];
    [dict setObject:self.locationModel.citycode?:@"" forKey:@"address_zip_code"];
    [dict setObject:self.locationModel.longitude?:@"" forKey:@"address_longitude"];
    [dict setObject:self.locationModel.latitude?:@"" forKey:@"address_latitude"];
    
    NSLog(@"提交的经度：%@ 提交的纬度：%@",self.locationModel.longitude,self.locationModel.latitude);
    
    if (self.isEdit) {
        [dict setObject:self.addressModel.address_id forKey:@"address_id"];
    }
    [[QYNetManager sharedManager]POST:kInsertAddress parameters:dict andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        [weakSelf endReresh];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            NSInteger result = [responseObject[@"data"] integerValue];
            if (weakSelf.isEdit) {
                if (responseObject[@"data"]) {
                    [weakSelf showSuccessWithType:0 AndTitle:@"修改成功"];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else{
                    [weakSelf showSuccessWithType:0 AndTitle:@"修改失败"];
                }
            }else{
                if (result) {
                    [weakSelf showSuccessWithType:0 AndTitle:@"添加成功"];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else{
                    [weakSelf showSuccessWithType:0 AndTitle:@"添加失败"];
                }
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf endReresh];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.keyArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 2) {
        DecorateAppointPositionSelectTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:PositionSelectIDentifier];
        cell.delegate = self;
        cell.nameLabel.text = self.keyArray[indexPath.row];
        [cell cellForLayout:self.valueArray[indexPath.row]];
        return cell;
    }else{
        DecorateAppointInputTextTableCell *cell = [self.tableView dequeueReusableCellWithIdentifier:InputTextIDentifier];
        cell.delegate = self;
        cell.indexPath = indexPath;
        cell.nameLabel.text = self.keyArray[indexPath.row];
        cell.textField.placeholder = self.placeArray[indexPath.row];
        cell.textField.text = self.valueArray[indexPath.row];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 150.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, F_DEVICE_W, 150)];
    backView.backgroundColor = [UIColor appColor];
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(30, 70, F_DEVICE_W - 60, 50);
    addButton.layer.cornerRadius = 6;
    addButton.layer.masksToBounds = YES;
    [addButton setBackgroundColor:[HSPublic colorWithHexString:@"333333"]];
    if (self.isEdit) {
        [addButton setTitle:@"保存地址" forState:UIControlStateNormal];
        [addButton setTitle:@"保存地址" forState:UIControlStateSelected];
    }else{
        [addButton setTitle:@"添加地址" forState:UIControlStateNormal];
        [addButton setTitle:@"添加地址" forState:UIControlStateSelected];
    }
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [addButton addTarget:self action:@selector(addNewAddress) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:addButton];
    return backView;
}


#pragma mark - DecorateTapSelectTableCellDelegate
/**
 地址选择
 */
- (void)tapPlaceTableCellEvent{
    [self.view endEditing:YES];
    BaseLocationManagerVC *location = [[BaseLocationManagerVC alloc]init];
    AutoWeakSelf
    location.locationBlock = ^(DecorateLocationModel *locationModel) {
        weakSelf.locationModel = locationModel;
        [weakSelf.valueArray replaceObjectAtIndex:2 withObject:weakSelf.locationModel.prefixArea];
        [weakSelf.valueArray replaceObjectAtIndex:3 withObject:weakSelf.locationModel.suffixArea];
        [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0],[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    TAB_PUSH(self, location, YES);
}

- (void)modifSingleTextFieldTableCell:(NSIndexPath *)indexPath WithEditEndText:(NSString *)text{
    if (k_Is_Empty(text)) {
        return;
    }
    [self.valueArray replaceObjectAtIndex:indexPath.row withObject:text];
    [self.tableView reloadData];
}

- (NSMutableArray *)keyArray{
    if (!_keyArray) {
        _keyArray = [NSMutableArray array];
    }
    return _keyArray;
}

- (NSMutableArray *)valueArray{
    if (!_valueArray) {
        _valueArray = [NSMutableArray array];
    }
    return _valueArray;
}

- (NSMutableArray *)placeArray{
    if (!_placeArray) {
        _placeArray = [NSMutableArray array];
    }
    return _placeArray;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
